#!/bin/bash
# 基于systemctl,安装myrpc-service

sh_folder="$(cd "$(dirname $0)"; pwd -P)"
# Default case for Linux sed, just use "-i"
sedi=(-i)
case "$(uname)" in
  # For macOS, use two parameters
  Darwin*) sedi=(-i "")
esac

# 修改$1指定的文件名中名为$2的值为$3
# $1 key=value格式保存变量值的文件名
# $2 变量名key
# $3 变量的值value
# 修改成功返回0, 失败退出脚本,$1 文件不存在则创建文件并添加key=value
function set_value(){
    if [ ! -f "$1" ]
    then 
        # 添加key=value对到文件
        [ ! -d "$(dirname $1)" ] && mkdir -p "$(dirname $1)"
        echo -e "\n$2=$3" >> $1 || exit
        return 0
    fi
    if grep -q -E "^\s*$2\s*=.*$" $1
    then
        local r="$3"
        r=${r//&/\\&}
        r=${r//!/\\!}
        r=${r//\//\\/}
        # 如果存在key=value定义，则修改定义,否则向文件添加定义
        sed "${sedi[@]}"  -r "s/(^\s*$2\s*=).*$/\\1$r/g" $1 || exit
        return 0
    fi
    if grep -q -E "^(#+\s*)+$2\s*=.*$" $1
    then
        local r="$3"
        r=${r//&/\\&}
        r=${r//!/\\!}
        # 如果存在#开头的key=value(无效)定义,添加key=value对到找到行之后
        sed "${sedi[@]}"  -r "/^(#+\s*)+$2\s*=.*$/a\\$2=$r" "$1" || exit
        return 0
    fi
    # 添加key=value对到文件
    bash -c "echo ;echo $2=$3 >> $1" || exit
    return 0  
}

SUDO=sudo
[ "$(whoami)" = root ] && SUDO=

pushd $sh_folder 1>/dev/null

cp -f myrpc.service.in myrpc.service || exit

service_file=myrpc.service

# 配置本地 myrpc 服务
# 如果服务存在，先停止服务
[ -z "$(systemctl list-unit-files --type=service | grep myrpc)" ] || $SUDO systemctl stop myrpc || exit
svr=/etc/systemd/system/myrpc.service
echo "创建 myrpc 服务脚本:$svr"
echo WorkingDirectory="$sh_folder"
set_value $service_file WorkingDirectory "$sh_folder" 
echo ExecStart="$sh_folder/myrpc start --hup"
set_value $service_file ExecStart "$sh_folder/myrpc start --hup" 
echo ExecStop="$sh_folder/myrpc stop"
set_value $service_file ExecStop "$sh_folder/myrpc stop"
User=$(whoami)
echo User=$User
set_value $service_file User "$User"
Group="$(id -gn)"
echo Group="$Group"
set_value $service_file Group "$Group"

$SUDO mv -f myrpc.service $svr || exit

$SUDO systemctl daemon-reload || exit
$SUDO systemctl enable myrpc || exit
$SUDO systemctl restart myrpc || exit

# $sh_folder
popd 1>/dev/null 
